 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=5 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:54 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Validate method arguments
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='assert,validate,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Validate method arguments</div>

<div class='main-body'>
 
<br>The first lines of a method are usually devoted to checking the validity
of method arguments. The idea is to fail as quickly as possible in the event
of an error. This is particularly important for constructors.

<P>It is a reasonable policy for a class to skip validating arguments of <tt>private</tt> methods. 
The reason is that <tt>private</tt> methods can only be called from the class itself. Thus, 
a class author should be able to confirm that all calls of a <tt>private</tt> method are valid. 
If desired, the <tt>assert</tt> keyword can be used to verify <tt>private</tt> method arguments, 
to check the internal consistency of the class. (Using <tt>assert</tt> for checking the arguments of
a non-<tt>private</tt> method is <a href="TopicActionbf65-2.html">not recommended</a>, since disabling such assertions
would mean the <a href='TopicAction63b6-2.html'>contract</a> of the non-<tt>private</tt> method is no longer being enforced.)

<p>When validating an argument, an <tt>Exception</tt> is thrown if the test fails.
This is often 
<tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/IllegalArgumentException.html">IllegalArgumentException</a></tt>,
<tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html">NullPointerException</a></tt>, 
or 
<tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/IllegalStateException.html">IllegalStateException</a></tt>.
These are all subclasses of <tt><a href="http://java.sun.com/javase/6/docs/api/java/lang/RuntimeException.html">RuntimeException</a></tt>. 
Checked exceptions may also be thrown,
as shown in the <a href="TopicAction0ec8-2.html">Model Object validation</a> topic. Many programmers
<a href="TopicActionf005-2.html">document these exceptions in the <tt>@throws</tt></a>
clause of the method's javadoc, since they clearly state the method's requirements
to the caller (the pre-conditions). Others, however, feel that 
<a href="TopicActioncd9b-2.html">manually documenting exceptions should be avoided</a>.

<p>If <em>every</em> object parameter of <em>every</em> method in a class needs to be non-null
in order to avoid throwing <tt>NullPointerException</tt>, then it's acceptable
to state this once in the general class javadoc, instead of repeating it
for each method. 

<P>Another alternative is to state in <tt>overview.html</tt>
(javadoc's summary description of an entire application) that <em>all</em> parameters
are to be considered non-null unless explicitly stated otherwise.


<p><b>Example 1</b>

<p>The constructor of this class validates its arguments before doing anything
else. If a validation fails, then an <tt>IllegalArgumentException</tt>
is thrown.
<br>
<PRE>

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ElementaryParticle {

  <span class='comment'>/**
  * @param aName has content.
  * @param aSpeed is in the range 0 (inclusive) to 1 (inclusive), and
  * is expressed as a fraction of the speed of light. (The photon is
  * an example of an elementary particle which travels at this speed.)
  * @exception IllegalArgumentException if a param does not comply.
  */</span>
  <span class='keyword'>public</span> ElementaryParticle ( String aName, <span class='keyword'>double</span> aSpeed ) {
    <span class='keyword'>if</span> ( !textHasContent(aName) ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Name has no content."</span>);
    }
    <span class='keyword'>if</span> ( aSpeed &lt; <span class='literal'>0.0</span> || aSpeed &gt; <span class='literal'>1.0</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Speed not in range [0..1]: "</span> + aSpeed);
    }
    fName = aName;
    fSpeed = aSpeed;
  }

  <span class='comment'>//..other methods elided
</span>
  <span class='comment'>// PRIVATE ////
</span>  <span class='keyword'>private</span> String fName;
  <span class='keyword'>private</span> <span class='keyword'>double</span> fSpeed;

  <span class='comment'>/**
  * Returns true if aText is non-null and has visible content.
  *
  * This is a test which is often performed, and should probably
  * be placed in a general utility class.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> textHasContent( String aText ){
    String EMPTY_STRING = <span class='literal'>""</span>;
    <span class='keyword'>return</span> (aText != <span class='keyword'>null</span>) &amp;&amp; (!aText.trim().equals(EMPTY_STRING));
  }
} 
</PRE>
<br>
<br><b>Example 2</b>
<p>Some validations are very common :
<ul>
<li>
check that an object is not <tt>null</tt></li>

<li>
check that text has visible content</li>

<li>
check that a number is in some range</li>
</ul>

Providing a class for such validations can often be useful. In this example,
the <tt>Args</tt> class throws <tt>IllegalArgumentException</tt> 
if a corresponding boolean check fails. Using <tt>Args</tt> to validate
arguments will increase legibility noticeably, especially in the case of
multiple validations.
<br>
<PRE>

<span class='keyword'>package</span> hirondelle.web4j.util;

<span class='keyword'>import</span> java.util.regex.*;

<span class='comment'>/**
 Utility methods for common argument validations.

&lt;P&gt;Replaces &lt;tt&gt;if&lt;/tt&gt; statements at the start of a method with 
 more compact method calls.
 
 &lt;P&gt;Example use case.
 &lt;P&gt;Instead of :
 &lt;PRE&gt;
 public void doThis(String aText){
   if (!Util.textHasContent(aText)){
     throw new IllegalArgumentException();
   }
   //..main body elided
 }
 &lt;/PRE&gt;
 &lt;P&gt;One may instead write :
 &lt;PRE&gt;
 public void doThis(String aText){
   Args.checkForContent(aText);
   //..main body elided
 }
 &lt;/PRE&gt;
*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Args {
  
  <span class='comment'>/**
   If &lt;code&gt;aText&lt;/code&gt; does not satisfy {@link Util#textHasContent}, then 
   throw an &lt;code&gt;IllegalArgumentException&lt;/code&gt;.
  
   &lt;P&gt;Most text used in an application is meaningful only if it has visible content.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForContent(String aText){
    <span class='keyword'>if</span>( ! Util.textHasContent(aText) ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Text has no visible content"</span>);
    }
  }

  <span class='comment'>/**
   If {@link Util#isInRange} returns &lt;code&gt;false&lt;/code&gt;, then 
   throw an &lt;code&gt;IllegalArgumentException&lt;/code&gt;. 
  
   @param aLow is less than or equal to &lt;code&gt;aHigh&lt;/code&gt;.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForRange( <span class='keyword'>int</span> aNumber, <span class='keyword'>int</span> aLow, <span class='keyword'>int</span> aHigh ) {
    <span class='keyword'>if</span> ( ! Util.isInRange(aNumber, aLow, aHigh) ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(aNumber + <span class='literal'>" not in range "</span> + aLow + <span class='literal'>".."</span> + aHigh);
    }
  }

  <span class='comment'>/**
   If &lt;tt&gt;aNumber&lt;/tt&gt; is less than &lt;tt&gt;1&lt;/tt&gt;, then throw an 
   &lt;tt&gt;IllegalArgumentException&lt;/tt&gt;.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForPositive(<span class='keyword'>int</span> aNumber) {
    <span class='keyword'>if</span> (aNumber &lt; <span class='literal'>1</span>) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(aNumber + <span class='literal'>" is less than 1"</span>);
    }
  }

  <span class='comment'>/**
   If {@link Util#matches} returns &lt;tt&gt;false&lt;/tt&gt;, then 
   throw an &lt;code&gt;IllegalArgumentException&lt;/code&gt;. 
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForMatch(Pattern aPattern, String aText){
    <span class='keyword'>if</span> ( ! Util.matches(aPattern, aText) ){
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(
        <span class='literal'>"Text "</span> + Util.quote(aText) + <span class='literal'>" does not match '"</span> +aPattern.pattern()+ <span class='literal'>"'"</span>
      );
    }
  }
  
  <span class='comment'>/**
   If &lt;code&gt;aObject&lt;/code&gt; is null, then throw a &lt;code&gt;NullPointerException&lt;/code&gt;.
  
   &lt;P&gt;Use cases :
  &lt;pre&gt;
   doSomething( Football aBall ){
     //1. call some method on the argument : 
     //if aBall is null, then exception is automatically thrown, so 
     //there is no need for an explicit check for null.
     aBall.inflate();
    
     //2. assign to a corresponding field (common in constructors): 
     //if aBall is null, no exception is immediately thrown, so 
     //an explicit check for null may be useful here
     Args.checkForNull( aBall );
     fBall = aBall;
     
     //3. pass on to some other method as parameter : 
     //it may or may not be appropriate to have an explicit check 
     //for null here, according the needs of the problem
     Args.checkForNull( aBall ); //??
     fReferee.verify( aBall );
   }
   &lt;/pre&gt;
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> checkForNull(Object aObject) {
    <span class='keyword'>if</span> ( aObject == <span class='keyword'>null</span> ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> NullPointerException();
    }
  }
  
  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> Args(){
    <span class='comment'>//empty - prevent construction
</span>  }
  
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction0d31-2.html?Id=6'>Validate state with class invariants</a> <br>
 
  
  <a href='TopicActionf005-2.html?Id=44'>Javadoc all exceptions</a> <br>
 
  
  <a href='TopicActionbf65-2.html?Id=100'>Assert is for private arguments only</a> <br>
 
  
  <a href='TopicActioncd9b-2.html?Id=171'>Avoid @throws in javadoc</a> <br>
 
  
  <a href='TopicActiond08d-2.html?Id=187'>Model Objects</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='5'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=5 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:56 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
